window.onload = function () {

    const file = document.getElementById("file");
    const audio = document.getElementById("audio");
    const title = document.getElementsByTagName('title')[0];

    file.onchange = function () {
        //part1: 画布
        const canvas = document.getElementById("canvas");
        const context = canvas.getContext("2d");

        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        const WIDTH = canvas.width;
        const HEIGHT = canvas.height;

        //part2: 音频
        const files = this.files;//声音文件
        title.text = files[0].name
        audio.src = URL.createObjectURL(files[0]);
        audio.load();

        //part3: 分析器
        const AudCtx = new AudioContext();//音频内容
        const src = AudCtx.createMediaElementSource(audio);
        const analyser = AudCtx.createAnalyser();

        src.connect(analyser);
        analyser.connect(AudCtx.destination);
        analyser.fftSize = 128;//快速傅里叶变换, 必须为2的N次方

        const bufferLength = analyser.frequencyBinCount;// = fftSize * 0.5

        //part4: 变量
        const barWidth = (WIDTH / bufferLength) - 1;//间隔1px
        let barHeight;

        const dataArray = new Uint8Array(bufferLength);//8位无符号定长数组

        //part5: 动态监听
        function renderFrame() {
            requestAnimationFrame(renderFrame);//方法renderFrame托管到定时器，无限循环调度，频率<16.6ms/次

            context.fillRect(0, 0, WIDTH, HEIGHT);//画布拓展全屏,动态调整

            analyser.getByteFrequencyData(dataArray);//获取当前时刻的音频数据

            //part6: 绘画声压条
            let x = 0;
            for (let i = 0; i < bufferLength; i++) {
                const data = dataArray[i];//int,0~255

                const percentV = data / 255;//纵向比例
                const percentH = i / bufferLength;//横向比例

                barHeight = HEIGHT * percentV;

                //gbk,0~255
                const r = 255 * percentV;//值越大越红
                const g = 255 * percentH;//越靠右越绿
                const b = 50;

                context.fillStyle = "rgb(" + r + "," + g + "," + b + ")";
                context.fillRect(x, HEIGHT - barHeight, barWidth, barHeight);

                x += barWidth + 1;//间隔1px
            }
        }

        renderFrame();

        //part7: 播放声音
        audio.play();
    };
};
